package com.tpsix.security.saas;

import com.baomidou.mybatisplus.extension.plugins.tenant.TenantHandler;
import com.tpsix.security.ProjectConfigurationProperties;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * 租户处理器 -主要实现mybatis-plus https://mp.baomidou.com/guide/tenant.html
 */
@Slf4j
@Component
@AllArgsConstructor
public class CustomTenantHandler implements TenantHandler {

    private final ProjectConfigurationProperties projectProperties;

    @Override
    public Expression getTenantId(boolean where) {
        Long tenantId = TenantContextHolder.getTenantId();
        log.debug("当前租户为: {}", tenantId);
        return new LongValue(tenantId);
    }

    /**
     *
     * @return 租户 id 字段名称
     */
    @Override
    public String getTenantIdColumn() {
        return projectProperties.getTenant().getTenantProperty();
    }

    /**
     * 根据表名判断是否进行过滤
     * 忽略掉一些表：如租户表（sys_tenant）本身不需要执行这样的处理
     *
     * @param tableName 表名
     * @return 是否过滤
     */
    @Override
    public boolean doTableFilter(String tableName) {
        return projectProperties.getTenant().getIgnoreTables().stream().anyMatch(temp -> temp.equals(tableName));
    }

}
